package com.deyuanyun.pic.settings.task.run;

import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;

import com.deyuanyun.pic.common.util.ThreadUtil;
import com.deyuanyun.pic.settings.controller.dto.SMSMessageVO;
import com.deyuanyun.pic.settings.support.utils.SMSUtils;
import com.deyuanyun.pic.settings.task.Pool;
import com.deyuanyun.pic.settings.task.StaticConsts;

/**
 * 短信发送服务
 * @author chace
 * Created by chace on 2016/4/2.
 */
public class SMSServiceRun implements Scheduledable {
    static Logger logger=Logger.getLogger(SMSServiceRun.class);
    private Map map;
    private String threadName;//线程名称后缀（同一个Tomcat下，部署到不同的应用中，线程可以被查到，会误会已经在运行，所以需要应用名称来作为线程后缀）
    
    @Override
    public void run() {

        boolean b=ThreadUtil.threadIsAliveByName(getScheduledType());
        if (b){
            System.out.println(getScheduledType()+">>>>>线程已经在运行");
            return;
        }
        if(map!=null){
            logger.error("任务"+getScheduledType()+">>"+ map.get("threadNum")+"开始运行>>>>>");
        }
        Thread.currentThread().setName(getScheduledType());

        for (;;){

            if (Pool.sms_mult_thread){
                break;
            }
            try {

                SMSMessageVO messageVO = Pool.SMS_QUEUE.take();
                System.out.println(">>>>>>>>"+messageVO.getPhone());
                SMSUtils.senSMS(messageVO);
            } catch (Exception e) {
                logger.error(">>短信发送异常:",e);
                continue;
            }
        }

        ThreadUtil.threadRunTime.remove(getScheduledType());
        Thread.currentThread().setName("thread_" + getScheduledType()+ RandomStringUtils.randomAlphanumeric(5));
        if(map!=null){
            logger.error("任务"+getScheduledType()+">>"+ map.get("threadNum")+"结束运行>>>>>");
        }
    }


    @Override
    public String getScheduledType() {
        return StaticConsts.SMS_SERVICE + threadName;
    }

    @Override
    public Integer crTimeMinu() {
        return null;
    }

    @Override
    public void setMark(Map x) {
        this.map=x;
    }

    @Override
    public Map getMark() {
        return this.map;
    }


    public String getThreadName() {
        return threadName;
    }


    public void setThreadName(String threadName) {
        this.threadName = threadName;
    }


}
